import json
import jwt
import datetime
from django.shortcuts import render

import time
from django.views import View
from django.http import JsonResponse
from .models import *

from rest_framework import viewsets


# from app.serilizer import UserInfoSerializer, RoleSerializer,UsersSerializer,tabsSerializer


# import execjs

# class UserViewSet(viewsets.ModelViewSet):
#     """
#     允许用户查看或编辑的API路径。
#     """
#     queryset = UserInfo.objects.all()
#     serializer_class = UserInfoSerializer
#
#     # def post(self):
#     def post(self, req):
#         return JsonResponse({"code": 200, "message": "添加成功"})
#
#
# class RoleViewSet(viewsets.ModelViewSet):
#     """
#     允许用户查看或编辑的API路径。
#     """
# queryset = Role.objects.all()
# serializer_class = RoleSerializer
# def post(self):
# def post(self,req):
#     return JsonResponse({"code":200,"message":"添加成功"})


# class UsersViewSet(viewsets.ModelViewSet):
#     queryset = Users.objects.all()
#     serializer_class = UsersSerializer
# class tabViewSet(viewsets.ModelViewSet):
#     queryset = tabs.objects.all()
#     serializer_class = tabsSerializer

# def get_des_pass(data):
#     jsstr = get_js()
#     ctx = execjs.compile(jsstr)
#     return ctx.call("decrypt", data)


def get_js():
    with open('../static/statu/aec.js', 'r', encoding="utf-8") as f:
        res = f.read()
    return res


# 登录
def Login(request):
    # print(d["tokens"])
    # try:
    if request.method == "POST":
        token = request.META.get("HTTP_AUTHORIZATION", "")
        print(token)
        if token:  # 如果携带token 进行token比对

            print('有token')
            try:
                user_dic = list(UserInfo.objects.filter(tokens=token.split(' ')[1]).values())[0]
            except:
                return JsonResponse({"code": 402, "message": "token无效"})
            if user_dic:  # 比对成功 直接登录，返回用户信息
                print(user_dic['status'])
                if user_dic['status'] == False:
                    return JsonResponse({"code": 304, "message": "该用户不可登录"})

                print('token有效')
                user_dic.pop('password')
                role_name = UserInfo.objects.filter(email=user_dic['email']).values("roles__title")[0]["roles__title"]
                print(role_name)

                return JsonResponse({"code": 200, "message": "登录成功", "user": user_dic, "data": {"roleName": role_name}})
            else:
                return JsonResponse({"code": 402, "message": "token无效"})
        else:  # 如果没有token  进行进行账号密码匹配，如果
            d = json.loads(request.body)

            user = list(UserInfo.objects.filter(email=d["email"]).values())[0]

            if user['status']:  # 判断登录状态  如果状态为True
                print('状态True')
                try:
                    print('没有token')
                    if d["email"] == user["email"] and d["password"] == user["password"]:
                        dic = {
                            "iat": int(time.time()),  # 创建时间
                            "exp": int(time.time()) + 7200,  # 过期时间
                            'iss': user["username"],
                            'data': {
                                "a": user["username"],
                                "b": user["password"],
                            }
                        }
                        s = jwt.encode(dic, "secret", algorithm='HS256')
                        # 解密token
                        ss = jwt.decode(s, "secret", issuer=user["username"], algorithms=['HS256'])
                        print(ss["iat"], '创建时间')
                        print(ss["exp"], '过期时间')
                        UserInfo.objects.filter(id=user["id"]).update(tokens=s, create_token=ss["iat"],
                                                                      end_token=ss["exp"])
                        ds = list(UserInfo.objects.filter(id=user["id"]).values())[0]
                        ds.pop("password", 'create_token')
                        roles__title = UserInfo.objects.filter(email=d["email"]).values("roles__title")
                        role_name = roles__title[0]["roles__title"]

                        return JsonResponse(
                            {"code": 200, "message": "登录成功", "user": ds, "data": {"roleName": role_name}})
                    else:
                        return JsonResponse({"code": 401, "message": "密码错误"})
                except IndexError:
                    return JsonResponse({"code": 402, "message": "没有找到该用户"})

            else:
                print('状态False')
                return JsonResponse({"code": 304, "message": "该用户不可登录"})

    return JsonResponse({"code": 500, "message": "服务端错误"})


# 权限管理
class Permissions(View):
    def post(self, req):
        body = json.loads(req.body)
        permisson = Role.objects.filter(title=body['title']).first()
        obj = list(permisson.permissions.all().values())
        authedRoutes = []
        for i in obj:
            authedRoutes.append(i['url'])
        return JsonResponse({"code": 200, "data": {"authedRoutes": authedRoutes}, "success": True, "message": '成功'})

    def get(self, req):
        data = Permission.objects.all().values()
        return JsonResponse({"code": 200, 'data': list(data)})

    def delete(self, req):
        id = req.GET.get("id")
        if id:
            Permission.objects.filter(id=id).delete()
            return JsonResponse({"code": 200, "message": "删除成功"})
        return JsonResponse({"code": "304", "message": "id不可为空"})

    def put(self, req):
        body = json.loads(req.body)
        Permission.objects.filter(id=body['id']).update(title=body['title'], icon=body['icon'], url=body['url'])
        return JsonResponse({"code": 200, 'message': "修改成功"})

    def patch(self, req):
        body = json.loads(req.body)
        print(body)
        Permission.objects.create(title=body['title'], icon=body['icon'], url=body['url'])
        return JsonResponse({"code": 200, 'message': "添加成功"})

        # 角色管理


class Roles(View):
    def post(self, req):
        data = json.loads(req.body)
        if data:
            Role.objects.create(title=data['roleName'], remark=data['remark'])
            return JsonResponse({"code": 200, "message": "添加成功"})
        else:
            return JsonResponse({"code": 304, "message": "不可为空"})

    def get(self, req):
        data = Role.objects.all().values()
        return JsonResponse({"code": 200, "message": "获取成功", "data": list(data)})

    def delete(self, req):
        id = req.GET.get("id")
        Role.objects.filter(id=id).delete()
        return JsonResponse({"code": 200, "message": "删除成功"})

    def put(self, req):
        data = json.loads(req.body)
        id = data['id']
        obj = Role.objects.filter(id=id).first()
        obj.permissions.clear()
        for i in data['da']:
            item = Permission.objects.filter(url=i).first()
            id = item.id
            obj.permissions.add(id)
        return JsonResponse({"code": 200, "message": "修改成功"})


# 根据角色ID获取 权限列表
def Permiss(request):
    if request.method == "GET":
        id = request.GET.get("id")
        obj = Role.objects.get(id=id)
        permisson = list(obj.permissions.all().values())
        return JsonResponse({"code": 200, "message": "获取成功", 'data': permisson})


# 用户
class UserInfos(View):
    def post(self, req):
        data = json.loads(req.body)
        print(data)
        try:
            UserInfo.objects.create(email=data['email'], password=data['password'], username=data['username'],
                                    nickname=data['nickname'], signature=data['signatrue'])
            user = UserInfo.objects.filter(email=data['email']).first()
            user.roles.add(data['roleId'])
            return JsonResponse({"code": 200, "message": "添加成功"})
        except:
            return JsonResponse({"code": 403, "message": "数据有误"})

    def get(self, req):
        data3 = UserInfo.objects.all().values('username', "status", "email", "last_login", "roles__title", "roles__id",
                                              "id",
                                              'signature', 'nickname')
        data_roles = Role.objects.all().values()
        return JsonResponse({"code": 200, "data": {'users': list(data3), 'roles': list(data_roles)}, "message": "获取成功"})

    def delete(self, req):
        id = req.GET.get("id")
        UserInfo.objects.filter(id=id).delete()
        return JsonResponse({"code": 200, "message": "删除成功"})

    def put(self, req):
        data = json.loads(req.body)
        print(data)
        if data:
            UserInfo.objects.filter(id=data['id']).update(email=data['email'], username=data['username'],
                                                          status=data['status'],
                                                          nickname=data['nickname'], signature=['signature'])
            obj = UserInfo.objects.filter(id=data['id']).first()
            obj.roles.clear()
            obj.roles.add(data['roles__id'])

            return JsonResponse({"code": 200, "message": "修改成功"})
        else:
            return JsonResponse({"code": 304, "message": "不可为空"})


# 题库
class Question(View):
    def get(self, req):
        data = Questions.objects.all().values("id", "title", "content", 'answer', 'types__typename', "types__id",
                                              'checked')
        data_type = Questiontype.objects.all().values()
        return JsonResponse({"code": 200, "data": {"data_list": list(data), "data_type": list(data_type)}})

    def post(self, req):
        try:
            data = json.loads(req.body)
            Question_obj = Questiontype.objects.filter(id=data['types__id']).first()
            Questions.objects.create(title=data['title'], content=data['content'], answer=data['answer'],
                                     types=Question_obj)
            return JsonResponse({"code": 200, "message": "添加成功"})
        except:
            return JsonResponse({"code": 405, "message": "数据有误"})

    def delete(self, req):
        id = req.GET.get("id")
        if id:
            Questions.objects.filter(id=id).delete()
        else:
            data = json.loads(req.body)
            for i in data:
                print(data[i])
                Questions.objects.filter(id=data[i]).delete()
            print(data)
        return JsonResponse({"code": 200, "message": "删除成功"})

    def put(self, req):
        try:
            data = json.loads(req.body)
            Questions.objects.filter(id=data['id']).update(title=data['title'], content=data['content'],
                                                           answer=data['answer'], types=data['types__id'])
            return JsonResponse({"code": 200, "message": "修改成功"})
        except:
            return JsonResponse({"code": 401, "message": "数据有误"})
    def patch(self,req):
        data = json.loads(req.body)
        Questiontype.objects.create(typename=data['typename'])
        return JsonResponse({"code": 405, "message": "添加成功"})
class QuestionTyp(View):
    def get(self,req):
        data=Questiontype.objects.all().values()
        return JsonResponse({"code": 200, "message": "获取成功",'data':list(data)})

    def post(self,req):
        try:
            data = json.loads(req.body)
            Questiontype.objects.create(typename=data['typename'])
            return JsonResponse({"code": 200, "message": "添加成功", })
        except:
            return JsonResponse({"code": 4111, "message": "数据有误", })
    def delete(self, req):
        try:
            id = req.GET.get("id")
            print(id)
            Questiontype.objects.filter(id=id).delete()
            return JsonResponse({"code": 200, "message": "删除成功",})
        except:
            return JsonResponse({"code": 123, "message": "数据有误", })
    def put(self,req):
        try:
            data = json.loads(req.body)
            Questiontype.objects.filter(id=data['id']).update(typename=data['typename'])
            return JsonResponse({"code": 200, "message": "修改成功",})
        except:
            return JsonResponse({"code": 777, "message": "数据有误", })


# class UsersView(View):
#     def get(self,req):
#         data=Users.objects.all().values()
#         return JsonResponse({"data":list(data)})
#     def delete(self,req):
#         id=req.GET.get('id')
#         print(id)
#         Users.objects.filter(id=id).delete()
#         return JsonResponse({"msg":"删除成功"})
#     def post(self,req):
#         data=json.loads(req.body)
#         print(data)
#         Users.objects.create(name=data['name'],yue=data['yue'])
#         return JsonResponse({"msg":"添加成功"})
#     def put(self,req):
#         id = req.GET.get('id')
#         data=json.loads(req.body)
#         Users.objects.filter(id=id).update(name=data['name'],yue=data['yue'])
#         return JsonResponse({"msg":"修改成功"})
#
# class TabsView(View):
#     def get(self,req):
#         data=tabs.objects.all().values()
#         return JsonResponse({"data":list(data)})
#     def post(self,req):
#         id = req.GET.get('id')
#         tabs.objects.filter(id=id).update(status='2')
#         return JsonResponse({"msg":"修改成功"})
#     def delete(self,req):
#         id = req.GET.get('id')
#         tabs.objects.filter(id=id).update(status='3')
#         return JsonResponse({"msg":"修改成功"})
#     def put(self,req):
#         id = req.GET.get('id')
#         tabs.objects.filter(id=id).update(status='1')
#         return JsonResponse({"msg":"修改成功"})
